// components/editor/editor.js
import http from '../../http'
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
let toast;
let num = 0
let timer;
Page({
	data: {
		formats: {},
		readOnly: false,
		placeholder: '开始输入...',
		editorHeight: 300,
		keyboardHeight: 0,
		isIOS: false,
		value: '',

		form: {},

		interval: 50,
		step: 1,
		num: 5,

		align: 'top',
		alignText: '靠上',
		alignShow: false,
		alignList: [{
			text: '靠上',
			value: 'top'
		}, {
			text: '居中',
			value: 'center'
		}, {
			text: '靠下',
			value: 'bottom'
		}],

		direction: 'right',
		directionText: '向右',
		directionShow: false,
		directionList: [{
			text: '向左',
			value: 'left'
		}, {
			text: '向右',
			value: 'right'
		}],

		// 下发结果
		issueResultBol: false,
		issueResult: [],
	},
	// websocket
	websocketLink() {
		toast = Toast.loading({
			duration: 0, // 持续展示 toast
			forbidClick: true,
			message: `请稍后(${num}/${this.data.form.factoryParams.length})`,
		});
		wx.connectSocket({
			url: http.screen + '/ws/screen/screenshot/shot',
			success: function () {
				console.log('WebSocket连接成功！')
			}
		})
		wx.onSocketOpen((res) => {
			console.log('WebSocket连接已打开！')
			console.log('参数', this.data.form);
			// 请求超时
			timer = setTimeout(() => {
				Toast.fail('请求超时')
				num = 0
				this.setData({
					issueResultBol: true,
					form: {
						command: undefined, //命令标识
						factoryParams: this.data.form.factoryParams,
						order: {} //命令内容 
					},
				})
				this.websocketClose()
			}, 7000);

			// 发送消息
			wx.sendSocketMessage({
				data: JSON.stringify(this.data.form)
			})
		})
		wx.onSocketMessage((res) => {
			console.log('收到服务器消息：', JSON.parse(res.data))
			let news = JSON.parse(res.data)
			num++
			let list = this.data.issueResult
			list = [...list, {
				name: news.sn,
				status: news.status
			}]
			this.setData({
				issueResult: list
			})
			console.log(num, this.data.form.factoryParams.length);
			if (num < this.data.form.factoryParams.length) {
				toast.setData({
					message: `请稍后(${num}/${this.data.form.factoryParams.length})`,
				});
			} else {
				clearTimeout(timer)
				// Toast.success('下发完成')
				Toast.clear()
				num = 0
				this.setData({
					issueResultBol: true,
					form: {
						command: undefined, //命令标识
						factoryParams: this.data.form.factoryParams,
						order: {} //命令内容
					},
				})
				this.websocketClose()
			}

		})
		wx.onSocketError(function (res) {
			console.log('WebSocket连接出错！')
			Toast.fail('连接出错');
		})
	},
	websocketClose() {
		wx.closeSocket()
		wx.onSocketClose(function (res) {
			console.log('WebSocket连接已关闭！')
		})
	},
	// 下发结果
	issueResultClose() {
		this.setData({
			issueResultBol: false,
			issueResult: []
		})
	},
	// 下发
	rollTextIssue() {
		let form = this.data.form
		form.command = 'scrollMarquee'
		form.order.interval = this.data.interval
		form.order.step = this.data.step
		form.order.num = this.data.num
		form.order.align = this.data.align
		form.order.direction = this.data.direction
		form.order.html = this.data.value
		this.setData({
			form: form
		}, () => {
			this.websocketLink()
		})
	},
	// 清屏
	clearScreen() {
		let form = this.data.form
		form.command = 'clear'
		this.setData({
			form: form
		}, () => {
			this.websocketLink()
		})
	},
	alignClick() {
		this.setData({
			alignShow: true
		})
	},
	alignConfirm(event) {
		this.setData({
			alignText: event.detail.value.text,
			align: event.detail.value.value,
			alignShow: false
		})
	},
	alignClose() {
		this.setData({
			alignShow: false
		})
	},
	directionClick() {
		this.setData({
			directionShow: true
		})
	},
	directionConfirm(event) {
		this.setData({
			directionText: event.detail.value.text,
			direction: event.detail.value.value,
			directionShow: false
		})
	},
	directionClose() {
		this.setData({
			directionShow: false
		})
	},
	input(event) {
		console.log(event.detail.html);
		this.setData({
			value: event.detail.html
		})
	},
	readOnlyChange() {
		this.setData({
			readOnly: !this.data.readOnly
		})
	},
	onEditorReady() {
		const that = this
		that.createSelectorQuery().select('#editor').context(function (res) {
			that.editorCtx = res.context
		}).exec()
	},
	onStatusChange(e) {
		const formats = e.detail
		console.log(e.detail);
		this.setData({
			formats
		})
	},
	calNavigationBarAndStatusBar() {
		const systemInfo = wx.getSystemInfoSync()
		const {
			statusBarHeight,
			platform
		} = systemInfo
		const isIOS = platform === 'ios'
		const navigationBarHeight = isIOS ? 44 : 48
		return statusBarHeight + navigationBarHeight
	},
	blur() {
		this.editorCtx.blur()
	},
	format(e) {
		let {
			name,
			value
		} = e.target.dataset
		if (!name) return
		console.log('format', name, value)
		this.editorCtx.format(name, value)

	},

	insertDivider() {
		this.editorCtx.insertDivider({
			success: function () {
				console.log('insert divider success')
			}
		})
	},
	clear() {
		this.editorCtx.clear({
			success: function (res) {
				console.log("clear success")
			}
		})
	},
	removeFormat() {
		this.editorCtx.removeFormat()
	},
	insertDate() {
		const date = new Date()
		const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
		this.editorCtx.insertText({
			text: formatDate
		})
	},
	insertImage() {
		const that = this
		wx.chooseImage({
			count: 1,
			success: function (res) {
				that.editorCtx.insertImage({
					src: res.tempFilePaths[0],
					data: {
						id: 'abcd',
						role: 'god'
					},
					width: '80%',
					success: function () {
						console.log('insert image success')
					}
				})
			}
		})
	},

	updatePosition(keyboardHeight) {
		const toolbarHeight = 50
		const {
			windowHeight,
			platform
		} = wx.getSystemInfoSync()
		let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
		this.setData({
			editorHeight,
			keyboardHeight
		})
	},
	onLoad() {
		const platform = wx.getSystemInfoSync().platform
		const isIOS = platform === 'ios'
		this.setData({
			isIOS
		})
		const that = this
		this.updatePosition(0)
		let keyboardHeight = 0
		wx.onKeyboardHeightChange(res => {
			if (res.height === keyboardHeight) return
			const duration = res.height > 0 ? res.duration * 1000 : 0
			keyboardHeight = res.height
			setTimeout(() => {
				wx.pageScrollTo({
					scrollTop: 0,
					success() {
						that.updatePosition(keyboardHeight)
						that.editorCtx.scrollIntoView()
					}
				})
			}, duration)
		})
	},
	onShow() {
		let pages = getCurrentPages()
		let currentPage = pages[pages.length - 1]
		let options = currentPage.options
		console.log(options);
		this.setData({
			form: JSON.parse(options.form),
		})
	}
})